/*******************************************************************************
 * Package: com.song.boot.springstudy.marshall
 * Type:    Client
 * Date:    2024-01-28 16:21
 *
 * Copyright (c) 2024 LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.boot.springstudy.netty.proto;

import com.song.boot.springstudy.netty.marshall.MarshallingCodec;
import com.song.boot.springstudy.netty.proto.protoDoMain.CatInfo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

/**
 * 功能描述：
 *
 * @author Songxianyang
 * @date 2024-01-28 16:21
 */
public class Client {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup workerEvent = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerEvent)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,128) // 设置线程队列
        .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                // 解码和编码，应和客户端一致
                //传输的协议 Protobuf
                socketChannel.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                socketChannel.pipeline().addLast(new ProtobufDecoder(CatInfo.CatMsg.getDefaultInstance()));
                socketChannel.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                socketChannel.pipeline().addLast(new ProtobufEncoder());
                socketChannel.pipeline().addLast(new ClientHandler());
            }
        });
        ChannelFuture connect = bootstrap.connect("127.0.0.1", 9999).sync();

        connect.channel().closeFuture().sync();

        workerEvent.shutdownGracefully();  // 关闭
    }
}
